# -*- coding:UTF-8 -*-
import serial #导入模块
import threading,time,string,os
import csv
#import asyncio

#from pynput.keyboard import Key,Listener
from shutil import *
import io

STRGLO="" #读取的数据
BOOL=True  #读取标志位
n=0

#读数代码本体实现
def ReadData(ser):
    global STRGLO,BOOL,n
    s = io.BytesIO()
        # 循环接收数据，此为死循环，可用线程实现
        #n=0    
    while BOOL:

            # "%01#RMB5A"25 30 31 23 52 4D 42 35 41 ]
            # %01#RMD5C  25 30 31 23 52 4d 44 35 43 0D

            #myinput=bytes([0X25,0X30,0X31,0X23,0X52,0X4D,0X42,0X35,0X41,0X0D]) # 需要发送的十六进制数据
            #ser.write(bytes([0X25,0X30,0X31,0X23,0X52,0X4D,0X42,0X35,0X41,0X0D]))  # %01#RMB5A写数据
             #   ser.write(bytes([0X25,0X30,0X31,0X23,0X52,0X4D,0X44,0X35,0X43,0X0D]))  # %01#RMD5C写数据
            
            if ser.in_waiting:
                STRGLO = ser.read(18)#ser.in_waiting)#.decode("utf-8")
                #print(STRGLO[7:15])
               # writer.writerow(STRGLO[7:15].split())#此处要进行格式转化不然一大堆分散
                #csvfile.flush()
                s.write(STRGLO)    
                time.sleep(0.0001)
                #n+=1
            

    DReadPort() #读串口数据      
    DColsePort(ser)  #关闭串口

    with open ('test.txt', 'wb') as fd:
      s.seek (0)
      copyfileobj (s, fd)
    s.close()
    fd.close()    
    #os.rename("test.txt","test3.csv")
             

#打开串口
# 端口，GNU / Linux上的/ dev / ttyUSB0 等 或 Windows上的 COM3 等
# 波特率，标准值之一：50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200
# 超时设置,None：永远等待操作，0为立即返回请求结果，其他值为等待超时时间(单位为秒）
def DOpenPort(portx,bps,timeout):
    ret=False
    try:
        # 打开串口，并得到串口对象
        ser = serial.Serial(portx, bps, timeout=timeout)
        #判断是否打开成功
        if(ser.is_open):
           ret=True
           threading.Thread(target=ReadData, args=(ser,)).start()
           threading.Thread(target=DWritePort, args=(ser,)).start()
           
    except Exception as e:
        print("---异常---：", e)
    return ser,ret

#关闭串口
def DColsePort(ser):
    global BOOL
    BOOL=False
    ser.close()

#写数据
def DWritePort(ser):
    while BOOL:
        ser.write(bytes([0X25,0X30,0X31,0X23,0X52,0X4D,0X44,0X35,0X43,0X0D]))  # %01#RMD5C写数据
        time.sleep(0.0001)        

#读数据
def DReadPort():
    global STRGLO
    str=STRGLO
    STRGLO=""#清空当次读取
    return str

#if __name__=="__main__":

ser,ret =DOpenPort("/dev/ttyS4",921600,None)
    
start = time.time()
time.sleep(300)
BOOL=False

end = time.time()
print (end-start)

print(str(n))




  
